package server.handler;

import server.service.SessionService;
import server.service.factories.SessionServiceFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class QuitHandler extends ChannelInboundHandlerAdapter {
    //当连接断开时触发
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        SessionService sessionService= SessionServiceFactory.getSessionService();
        Channel channel = ctx.channel();
        String username = sessionService.getUsername(channel);
        sessionService.unbind(channel);//要写在后面，不然获取不了用户名
        log.debug("{}已经断开", username);
//        super.channelInactive(ctx);
    }

    //当触发异常时
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        SessionService sessionService= SessionServiceFactory.getSessionService();
        Channel channel = ctx.channel();
        String username = sessionService.getUsername(channel);
        sessionService.unbind(channel);//要写在后面，不然获取不了用户名
        log.debug("{}已经异常断开，异常是:{}", username,cause.getMessage());
//        super.exceptionCaught(ctx, cause);
    }
}
